package com.feather.unit;

import java.util.List;
import java.util.Map;

import javax.sql.DataSource;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;

import com.feather.annotation.*;

public class SQLActionUnit {
	
	private DataSource dataSource;
	
	private JdbcTemplate jdbcTemplate;
	
	private NamedParameterJdbcTemplate jdbcTemplateNamed;
	
	@ActionMethod
	public Object sqlQueryList(
			@InputParam(name="sql") String sql,
			@InputParam(name="params") Map<String, Object> params) throws Exception
	{
		return params != null && params.size() > 0 
				? jdbcTemplateNamed.queryForList(sql, params)
				: jdbcTemplate.queryForList(sql);
	}
	
	@ActionMethod
	public Object sqlQueryObject(
			@InputParam(name="sql") String sql,
			@InputParam(name="params") Map<String, Object> params)
	{
		List<Map<String, Object>> result = params != null && params.size() > 0
				? jdbcTemplateNamed.queryForList(sql, params)
				: jdbcTemplate.queryForList(sql);
				
		if(result.size() > 0)
			return result.get(0);
		else
			return null;
	}
	
	@ActionMethod
	public Object sqlQueryOne(
			@InputParam(name="sql") String sql,
			@InputParam(name="params") Map<String, Object> params)
	{
		List<Map<String, Object>> result = params != null && params.size() > 0
				? jdbcTemplateNamed.queryForList(sql, params)
				: jdbcTemplate.queryForList(sql);
				
		if(result.size() > 0)
			return result.get(0).values().toArray()[0];
		else
			return null;
	}
	
	@ActionMethod
	public Object sqlQueryString(
			@InputParam(name="sql") String sql,
			@InputParam(name="params") Map<String, Object> params)
	{
		Object result = sqlQueryOne(sql, params);
		if(result == null)
			return null;
		if(result instanceof String)
			return result;
		
		return result.toString();
	}
	
	@ActionMethod
	public Object sqlUpdate(
			@InputParam(name="sql") String sql,
			@InputParam(name="params") Map<String, Object> params)
	{
		return jdbcTemplateNamed.update(sql, params);
	}

	public DataSource getDataSource() {
		return dataSource;
	}

	public void setDataSource(DataSource dataSource) {
		this.dataSource = dataSource;
		jdbcTemplate = new JdbcTemplate(dataSource);
		jdbcTemplateNamed = new NamedParameterJdbcTemplate(dataSource);
	}
}
